package com.myrpc.provider.registry;

import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.myrpc.common.Contants;

@Component
@Slf4j
public class ServiceRegistry {

    @Value("${registry.address}")
    private String registryAddress;
    
    private ZkClient client = null;


    public void register(String data) {
        if (data != null) {
             client = connectServer();
            if (client != null) {
                AddRootNode(client);
                createNode(client, data);
            }
        }
    }
    private ZkClient connectServer() {
    	if(client == null){
    		client = new ZkClient(registryAddress,20000,20000);
    	}
        return client;
    }

    private void AddRootNode(ZkClient client){
        boolean exists = client.exists(Contants.ZK_REGISTRY_PATH);
        if (!exists){
        	 // 将数据写入节点
            client.createPersistent(Contants.ZK_REGISTRY_PATH);
            log.info("创建zookeeper主节点 {}",Contants.ZK_REGISTRY_PATH);
        }
    }

    private void createNode(ZkClient client, String data) {//"/provider" dobbo application name
        String path = client.create(Contants.ZK_REGISTRY_PATH + "/user", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        
        //创建zookeeper数据节点 (/myrpc/provider0000000005 => 127.0.0.1:18868)
        log.info("创建zookeeper数据节点 ({} => {})", path, data);
    }
    
    public List<String> tsShowAllNode(){
    	if(client != null){
    		client = connectServer();
    	}
    	List<String> children = client.getChildren(Contants.ZK_REGISTRY_PATH);
    	return children;
    }
    
}
